package com.zx.tradeclient.ctrl.index2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.entity.GoodsInfo;

public class Index2GridList {
	private LoadMoreListViewWithProgress allView;
	private LoadMoreListView listView;
	private HomePageRankingAdapter adapter;
	private List<GoodsInfo> goods;
	private Context context;
	private int currentPage;
	private int totalPage;
	private TradeApp app;
	private String type;
	private int perPageCount = 14;
	private boolean reload = true;

	private static class ViewHolder {
		public TextView goods_name;
		public TextView goods_number_type;
		public TextView goods_number;
		public TextView goods_date;
		public TextView goods_price;
		public TextView goods_address;
		public RelativeLayout goods_layout;
		public ImageView goods_icon;
	}

	/**
	 * 
	 * @param context
	 * @param view
	 * @param type
	 *            1==ranking 2=recommend 3=essential
	 */
	public Index2GridList(Context con, View view, String types) {
		this.app = (TradeApp) con.getApplicationContext();
		this.context = con;
		this.type = types;
		this.currentPage = 0;
		this.totalPage = 0;

		perPageCount = 10 /* (int) Math.ceil(height / px) */;

		// 获取手机联网状态
		goods = new ArrayList<GoodsInfo>();

		allView = (LoadMoreListViewWithProgress) view;
		listView = (LoadMoreListView) allView.getListView();
		listView.setDivider(context.getResources().getDrawable(R.drawable.divider));
		listView.setSelector(context.getResources().getDrawable(R.drawable.list_item_colorexchange));
		listView.setDividerHeight(2);
		adapter = new HomePageRankingAdapter(context);
		listView.setAdapter(adapter);
		reload(true);
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask(type);
			}
		});

	}

	public void reload(boolean newload) {
		if (app.isNetWorkConnection && reload && !newload) {
			reload = false;
			allView.loading();
			loadDataTask(this.type);
		} else if (newload) {
			goods.clear();
			currentPage = 0;
			totalPage = 0;
			perPageCount = 10 /* (int) Math.ceil(height / px) */;
			reload = false;
			allView.loading();
			loadDataTask(this.type);
		} else {
			allView.show();
		}
	}

	// AsyncTask
	private void loadDataTask(String type) {
		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();

		map.put("act", "supplyDemandList");
		if (type.equals("2")) {
			map.put("way", "11");
		} else if (type.equals("3")) {
			map.put("way", "00");
		}
		if (app.product_rating.getCategory_id() != "") {
			map.put("cityId", app.product_rating.getCategory_id());
		}
		if (app.product_rating.getCategory_id() != "") {
			map.put("productTypeMin", app.product_rating.getCategory_id());
		}
		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				prase(response);

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void prase(JSONObject response) {
		if (goods.size() > 0) {
			reload = false;
		} else {
			reload = true;
		}
		try {

			String succeed = response.getString("succeed");
			if (succeed.equals("000")) {
				JSONObject userData = response;
				currentPage = userData.getInt("currentPage");
				totalPage = userData.getInt("totalPage");
				if (currentPage == totalPage) {
					listView.loadComplete(false);
				} else {
					listView.loadComplete(true);
				}

				JSONArray jsonArray = new JSONArray(userData.getString("dataList"));
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);

					GoodsInfo good = new GoodsInfo();

					good.setGoods_id(jsonObject.getString("id"));
					good.setGoods_name(jsonObject.getString("productname"));
					good.setGoods_price(jsonObject.getString("price"));
					good.setGoods_number(jsonObject.getString("num"));
					good.setGoods_site(jsonObject.getString("location"));
					good.setGoods_phone(jsonObject.getString("mobile"));
					String date = jsonObject.getString("createtime");
					if((date == null) || (date.equals(""))){
						date = "";
					}
					if(date.length() > 10){
						date = date.substring(0,  10);
					}
					good.setGoods_date(date);
					good.setGoods_number_type(jsonObject.getString("way"));
					// 添加内容
					goods.add(good);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (goods.size() > 0) {
			reload = false;
		}
		// We need notify the adapter that the data have been changed
		adapter.notifyDataSetChanged();
		allView.show();
	}

	// BaseAdapter
	private class HomePageRankingAdapter extends BaseAdapter {

		private LayoutInflater mlinflater;
		private ViewHolder holder = null;

		public HomePageRankingAdapter(Context context) {
			this.mlinflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return goods.size();
		}

		@Override
		public Object getItem(int position) {
			return Integer.valueOf(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup viewGroup) {

			final GoodsInfo goodsItem = goods.get(position);

			if (view == null) {

				view = mlinflater.inflate(R.layout.goods_item, null);
				holder = new ViewHolder();
				holder.goods_icon = (ImageView) view.findViewById(R.id.index2_goods_icon);
				holder.goods_name = (TextView) view.findViewById(R.id.index2_goods_name);
				holder.goods_number_type = (TextView) view.findViewById(R.id.index2_goods_number_type);
				holder.goods_number = (TextView) view.findViewById(R.id.index2_goods_number);
				holder.goods_date = (TextView) view.findViewById(R.id.index2_goods_date);
				holder.goods_price = (TextView) view.findViewById(R.id.index2_goods_price);
				holder.goods_address = (TextView) view.findViewById(R.id.index2_goods_address);
				holder.goods_layout = (RelativeLayout) view.findViewById(R.id.index2_goods_line);

				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			if (goodsItem != null) {
				holder.goods_name.setText(goodsItem.getGoods_name());
				if (goodsItem.getGoods_number_type().equals("00")) {
					holder.goods_number_type.setText(R.string.buy_info_number);
					holder.goods_icon.setBackgroundResource(R.drawable.icon_want);
				} else if (goodsItem.getGoods_number_type().equals("11")) {
					holder.goods_number_type.setText(R.string.supply_info_number);
					holder.goods_icon.setBackgroundResource(R.drawable.icon_supply);
				}

				holder.goods_number.setText(goodsItem.getGoods_number());
				holder.goods_date.setText(goodsItem.getGoods_date());
				holder.goods_price.setText(goodsItem.getGoods_price());
				holder.goods_address.setText(goodsItem.getGoods_site());

				holder.goods_layout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						if (app.isNetWorkConnection) {

							if (goodsItem.getGoods_number_type().equals("00")) {
								Intent intent = new Intent(context, BuyInfoActivity.class);
								intent.putExtra("productid", goodsItem.getGoods_id());
								((Index2Activity) context).startActivity(intent);
							} else if (goodsItem.getGoods_number_type().equals("11")) {
								Intent intent = new Intent(context, SupplyInfoActivity.class);
								intent.putExtra("productid", goodsItem.getGoods_id());
								((Index2Activity) context).startActivity(intent);
							}

						} else {
							Toast toast2 = Toast.makeText(context, "网络连接断开，请检查网络", Toast.LENGTH_SHORT);
							toast2.setGravity(Gravity.CENTER, 0, 0);
							toast2.show();
						}

					}
				});
			}

			return view;

		}

	}

}
